package com.example.strategy;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.example.entity.DbBlock;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Copyright: Copyright (c) 2022
 *
 * <p>
 * Description:
 *
 * @author LiuFeng
 * @version 2022/11/14 9:33
 * @since
 */
@Component
public class PLCDataConvertStrategyFactory implements ApplicationContextAware {
    /**
     * 存放数据转化的实现类
     */
    private Map<String, PLCDataConvertStrategy> map = new ConcurrentHashMap();

    /**
     * 将PLCDataConvertStrategy的实现类装配到map中，供后续工厂调用
     *
     * @param applicationContext 上下文
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, PLCDataConvertStrategy> beans = applicationContext.getBeansOfType(PLCDataConvertStrategy.class);
        beans.values().forEach(strategy -> map.put(strategy.getType(), strategy));
    }

    public String convertData(DbBlock dbBlock) {
        PLCDataConvertStrategy plcDataConvertStrategy = map.get(dbBlock.getType());
        if (plcDataConvertStrategy != null) {
            return plcDataConvertStrategy.convert(dbBlock);
        }
        return null;
    }
}
